import { ref, computed, watch, onUnmounted } from "vue";
import type { Ref } from "vue";
import { useDebounceFn } from "@vueuse/core";

// 缓存接口
interface CacheItem<T> {
  data: T[];
  total: number;
  timestamp: number;
}

// 重试配置接口
interface RetryConfig {
  maxRetries: number;
  retryDelay: number;
}

// 缓存配置接口
interface CacheConfig {
  enabled: boolean;
  ttl: number; // 缓存生存时间（毫秒）
}

interface PaginationParams {
  page: number;
  pageSize: number;
  [key: string]: any; // 允许额外的查询参数
}

interface PaginationOptions<T> {
  fetchFn: (params: PaginationParams) => Promise<{
    list: T[];
    total: number;
  }>;
  initialPage?: number;
  initialPageSize?: number;
  initialFilters?: Record<string, any>;
  initialSort?: { field: string; order: "asc" | "desc" } | null;
  immediate?: boolean;
  debounceTime?: number; // 防抖延迟时间（毫秒）
  retry?: RetryConfig; // 重试配置
  cache?: CacheConfig; // 缓存配置
}

export default function useAdminPagination<T>(options: PaginationOptions<T>) {
  const {
    fetchFn,
    initialPage = 1,
    initialPageSize = 20,
    initialFilters = {},
    initialSort = null,
    immediate = true,
    debounceTime = 300,
    retry = { maxRetries: 3, retryDelay: 1000 },
    cache = { enabled: true, ttl: 5 * 60 * 1000 }, // 默认缓存5分钟
  } = options;

  // 缓存存储
  const dataCache = new Map<string, CacheItem<T>>();

  // 请求锁
  const isLocked = ref(false);

  // 分页状态
  const currentPage = ref(initialPage);
  const pageSize = ref(initialPageSize);
  const data: Ref<T[]> = ref([]);
  const totalItems = ref(0);
  const isLoading = ref(false);
  const error = ref<Error | null>(null);

  // 筛选和排序
  const filters = ref<Record<string, any>>(initialFilters);
  const sort = ref<{ field: string; order: "asc" | "desc" } | null>(initialSort);

  // 计算属性
  const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value));
  const hasNextPage = computed(() => currentPage.value < totalPages.value);
  const hasPrevPage = computed(() => currentPage.value > 1);
  const paginationParams = computed(() => ({
    page: currentPage.value,
    pageSize: pageSize.value,
    ...filters.value,
    ...(sort.value ? { sortField: sort.value.field, sortOrder: sort.value.order } : {}),
  }));

  // 获取数据
  const fetchDataWithRetry = async (retryCount = 0): Promise<{ list: T[]; total: number }> => {
    try {
      return await fetchFn(paginationParams.value);
    } catch (err) {
      if (retryCount < retry.maxRetries) {
        await new Promise((resolve) => setTimeout(resolve, retry.retryDelay));
        return fetchDataWithRetry(retryCount + 1);
      }
      throw err;
    }
  };

  // 检查缓存
  const getCachedData = (params: PaginationParams): CacheItem<T> | null => {
    if (!cache.enabled) return null;
    const cacheKey = JSON.stringify(params);
    const cachedItem = dataCache.get(cacheKey);
    if (cachedItem && Date.now() - cachedItem.timestamp < cache.ttl) {
      return cachedItem;
    }
    return null;
  };

  // 设置缓存
  const setCacheData = (params: PaginationParams, data: { list: T[]; total: number }) => {
    if (!cache.enabled) return;
    const cacheKey = JSON.stringify(params);
    dataCache.set(cacheKey, { data: data.list, total: data.total, timestamp: Date.now() });
  };

  // 获取数据的防抖处理
  const debouncedFetchData = useDebounceFn(async () => {
    if (isLocked.value || isLoading.value) return;
    isLocked.value = true;
    isLoading.value = true;
    error.value = null;

    try {
      // 检查缓存
      const cachedData = getCachedData(paginationParams.value);
      if (cachedData) {
        data.value = cachedData.data;
        totalItems.value = cachedData.total;
        return;
      }

      // 获取新数据
      const { list, total } = await fetchDataWithRetry();
      data.value = list;
      totalItems.value = total;

      // 更新缓存
      setCacheData(paginationParams.value, { list, total });
    } catch (err) {
      error.value = err as Error;
      // 重置数据状态
      data.value = [];
      totalItems.value = 0;
      console.error("分页数据获取失败:", err);
    } finally {
      isLoading.value = false;
      isLocked.value = false;
    }
  }, debounceTime);

  const fetchData = () => {
    debouncedFetchData();
  };

  // 分页操作
  const nextPage = () => {
    if (hasNextPage.value) {
      currentPage.value++;
    }
  };

  const prevPage = () => {
    if (hasPrevPage.value) {
      currentPage.value--;
    }
  };

  const goToPage = (page: number) => {
    if (page >= 1 && page <= totalPages.value) {
      currentPage.value = page;
    }
  };

  const setPageSize = (size: number) => {
    pageSize.value = size;
    currentPage.value = 1; // 切换每页条数时回到第一页
  };

  // 筛选操作
  const updateFilter = (field: string, value: any) => {
    filters.value = { ...filters.value, [field]: value };
    currentPage.value = 1; // 筛选时回到第一页
  };

  const resetFilters = () => {
    filters.value = { ...initialFilters };
    currentPage.value = 1;
  };

  // 排序操作
  const toggleSort = (field: string) => {
    if (sort.value?.field === field) {
      sort.value.order = sort.value.order === "asc" ? "desc" : "asc";
    } else {
      sort.value = { field, order: "asc" };
    }
    currentPage.value = 1; // 排序时回到第一页
  };

  const resetSort = () => {
    sort.value = initialSort;
    currentPage.value = 1;
  };

  // 重置所有状态
  const resetAll = () => {
    currentPage.value = initialPage;
    pageSize.value = initialPageSize;
    filters.value = { ...initialFilters };
    sort.value = initialSort;
  };

  // 监听参数变化自动获取数据
  watch(
    [currentPage, pageSize, filters, sort],
    () => {
      fetchData();
    },
    { immediate, deep: true }
  );

  // 组件卸载时清理
  onUnmounted(() => {
    dataCache.clear();
  });

  return {
    // 状态
    currentPage,
    pageSize,
    data,
    totalItems,
    isLoading,
    error,
    filters,
    sort,

    // 计算属性
    totalPages,
    hasNextPage,
    hasPrevPage,
    paginationParams,

    // 方法
    fetchData,
    nextPage,
    prevPage,
    goToPage,
    setPageSize,
    updateFilter,
    resetFilters,
    toggleSort,
    resetSort,
    resetAll,
  };
}
